import {ref, type UnwrapRef} from 'vue'
import {defineStore} from 'pinia'
import {cacheKeys} from '@/stores/constant/cacheKey'
import type {RouteParamsRaw} from 'vue-router'
import router from '@/router'

export const useRouteParamsStore = defineStore(cacheKeys.ROUTE_PARAMS, () => {

			/**
			 * 路由参数，key为路由名称，value为路由参数
			 * 使用后应及时移除
			 */
			const routeParams = ref<Record<string, RouteParamsRaw>>({})

			const setParams = (params: RouteParamsRaw, routeName?: string) => {
				routeParams.value[routeName ?? <string>router.currentRoute.value.name] = params
			}

			const getParams = (routeName?: string): UnwrapRef<RouteParamsRaw> | undefined => {
				return routeParams.value[routeName ?? <string>router.currentRoute.value.name]
			}

			const removeParams = (routeName?: string) => {
				delete routeParams.value[routeName ?? <string>router.currentRoute.value.name]
			}

			const resetRouteParamsStore = () => {
				routeParams.value = {}
			}

			return {
				routeParams: routeParams,
				setParams: setParams,
				getParams: getParams,
				removeParams: removeParams,
				resetRouteParamsStore: resetRouteParamsStore
			}
		},
		{
			persist: {
				key: cacheKeys.ROUTE_PARAMS,
				storage: window.sessionStorage
			}
		}
)
